package com.phkj.qdh.net

import android.content.Context
import android.net.ConnectivityManager
import com.google.gson.JsonSyntaxException
import com.phkj.qdh.App
import rxhttp.wrapper.exception.HttpStatusCodeException
import rxhttp.wrapper.exception.ParseException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/**
 * FileName: NetExt
 * Author: rain
 * Date: 2020/7/3 1:04 PM
 * Description:
 * Email: zjhz7890@163.com
 */
val Throwable.code: Int
    get() {
        val errorCode = when (this) {
            is HttpStatusCodeException -> this.statusCode //Http状态码异常
            is ParseException -> this.errorCode     //业务code异常
            else -> "-1"
        }
        return try {
            errorCode.toString().toInt()
        } catch (e: Exception) {
            -1
        }
    }

val Throwable.msg: String?
    get() {
        var msg = handleNetworkException(this)
        if (this is HttpStatusCodeException) {
            //请求失败异常
            msg = "Http状态码异常"
        } else if (this is ConnectException) {
            msg = "网络异常，请检查是否连接网络！"
        } else if (this is JsonSyntaxException) {
            //请求成功，但Json语法异常,导致解析失败
            msg = "数据解析失败,请检查数据是否正确"
        } else if (this is ParseException) {
            // ParseException异常表明请求成功，但是数据不正确
            msg = this.message ?: errorCode
            //msg为空，显示code
        } else if (this is UnsupportedOperationException && this.message == "JsonObject") {
            msg = "数据解析失败,联系开发人员处理"
        }
        return msg
    }

//处理网络异常
private fun <T> handleNetworkException(throwable: T): String? {
    val stringId =
        if (throwable is UnknownHostException) {
            //网络异常
            if (!isNetworkConnected(App.CONTEXT)) "当前无网络，请检查你的网络设置" else "网络连接不可用，请稍后重试"
        } else if (throwable is SocketTimeoutException || throwable is TimeoutException) {
            //前者是通过OkHttpClient设置的超时引发的异常，后者是对单个请求调用timeout方法引发的超时异常
            "连接超时,请稍后再试"
        } else if (throwable is ConnectException) {
            //连接异常
            "网络不给力，请稍候重试"
        } else {
            "-1"
        }
    return if (stringId == "-1") null else stringId
}

private fun isNetworkConnected(context: Context): Boolean {
    val mConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val mNetworkInfo = mConnectivityManager.activeNetworkInfo
    if (mNetworkInfo != null) {
        return mNetworkInfo.isAvailable
    }
    return false
}
